package com.hk.service.quartz;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.hk.commons.entity.yingmi.YingmiConfirmFile;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.service.yingmi.IYingmiConfirmFile;


public class YingmiConfirmFileQuartz extends BaseQuartz {

	private Logger logger = LoggerFactory
			.getLogger(YingmiConfirmFileQuartz.class);

	@Autowired
	private YingmiApiUtils utils;

	@Autowired
	private IYingmiConfirmFile orderFielService;

	@Value("${yingmi.file.host}")
	private String host;

	@Value("${yingmi.data.file}")
	private String fileSave;

	@Override
	public void start() {
		/**
		 * /file/yingmi_<商户号>_order_<YYYYMMDD>.txt
		 */
		SimpleDateFormat sf = new SimpleDateFormat("YYYMMdd");
		String date = sf.format(System.currentTimeMillis());
		String path = "yingmi_" + "1017" + "_confirm_" + date;
		Map<String, String> params = new HashMap<>();
		String fileName = path + ".txt";
		String fileStr = utils.fileGet("/file/" + fileName, params, host);
		logger.info("get YingmiConfirmFile name={}",fileName);

		// 生成订单流文件
		Path filePath = Paths.get(fileSave + fileName);
		if (!Files.exists(Paths.get(fileSave + fileName))) {
			try {
				Files.write(filePath, fileStr.getBytes("UTF-8"));

				ExecutorService executor = Executors.newFixedThreadPool(1);
			    Runnable task = new Runnable() {
			        public void run() {
			           saveOrderDate(fileName);
			        }
			    };
			    executor.execute(task);
			    executor.shutdown();
			} catch (IOException e) {
				logger.error("file:{} error:{}", fileName, e);
			}
		}
	}

	private void saveOrderDate(String fileName) {
		List<String> list = new ArrayList<>();
		try {
			 list = Files.lines(Paths.get(fileSave + fileName)).collect(Collectors.toList());
			 String[] ss = null;
			 for (int i = 2; i < list.size(); i++) {
				 YingmiConfirmFile yof = new YingmiConfirmFile();
				 ss = StringUtils.splitPreserveAllTokens(list.get(i), '|');
				 yof.setBrokerUserId(ss[1]);
				 yof.setAccountId(ss[2]);
				 yof.setBrokerOrderNo(ss[3]);
				 yof.setOrderId(ss[4]);
				 yof.setPaymentMethodId(ss[5]);
				 yof.setCts(ss[6]);
				 yof.setTransactionCts(ss[7]);
				 yof.setConfirmCts(ss[8]);
				 yof.setFundCode(ss[9]);
				 yof.setShareType(ss[10]);
				 yof.setFundOrderCode(ss[11]);
				 yof.setChangeFundCode(StringUtils.isEmpty(ss[12]) ? "" : ss[12]);
				 yof.setChangeShareType(StringUtils.isEmpty(ss[13]) ? "" : ss[13]);
				 yof.setAppliedAmount(StringUtils.isEmpty(ss[14]) ?  new BigDecimal(0) : new BigDecimal(ss[14]));
				 yof.setConfirmShare(StringUtils.isEmpty(ss[15]) ? new BigDecimal(0) : new BigDecimal(ss[15]));
				 yof.setPayStatus(StringUtils.isEmpty(ss[16]) ?  0 : Integer.valueOf(ss[16]));
//				 yof.setOrderStatus(StringUtils.isEmpty(ss[17]) ?  0 : Integer.valueOf(ss[17]));
				 yof.setConfirmStatus(StringUtils.isEmpty(ss[17]) ?  0 : Integer.valueOf(ss[17]));
				 yof.setOrderDetail(StringUtils.isEmpty(ss[18]) ? "" : ss[18]);
				 yof.setSuccAmount(StringUtils.isEmpty(ss[19]) ? new BigDecimal(0) : new BigDecimal(ss[19]));
				 yof.setSuccShare(StringUtils.isEmpty(ss[20]) ? new BigDecimal(0) : new BigDecimal(ss[20]));
				 yof.setChangeSuccAmount(StringUtils.isEmpty(ss[21]) ? new BigDecimal(0) : new BigDecimal(ss[21]));
				 yof.setChangeSuccShare(StringUtils.isEmpty(ss[22]) ? new BigDecimal(0) : new BigDecimal(ss[22])); 
				 yof.setPoundage(StringUtils.isEmpty(ss[23]) ? new BigDecimal(0) : new BigDecimal(ss[23]));
				 yof.setTaNumers(StringUtils.isEmpty(ss[24]) ? "" : ss[24]);
				 orderFielService.add(yof);
			 }
		} catch (Exception e) {
			e.printStackTrace();
//			logger.error("fileName :{} saveOrderDate fail : {}", fileName, e);
		}

	}

}
